SQL Injection
範例
code:php
$sql = "select * from orders where status = {$status} and user = {$self}";
$stmt = $pdo->query($sql);
$data = [];
while ( $row = $stmt->fetch(PDO::FETCH_ASSOC) ) {
$data[] = $row;
}
攻擊:$_GET['status']傳入1 or 1 = 1; select * from orders where 1 = 1
執行的SQL會變成:select * from orders where stasus = 1 or 1 = 1; select * from orders where 1 = 1 and user = 123
導致所有資料流出
對策:改為參數化查詢,escape文字內容
code:php
$sql = "select * from orders where status = :status and user = :user";
$stmt = $pdo->prepare($sql);
$stmt->execute([
':status' => $status,
':user' => $self,
]);
$data = [];
while ( $row = $stmt->fetch(PDO::FETCH_ASSOC) ) {
$data[] = $row;
}